package com.itzmn.newcode.offer1;

import java.util.ArrayList;
import java.util.Collections;

/**
 * @Author: 张梦楠
 * @Date: 2018/12/18 10:47
 * 简书：https://www.jianshu.com/u/d611be10d1a6
 * 码云：https://gitee.com/zhangqiye
 * @Description: 从尾到头打印链表
 *
 * 输入一个链表，按链表值从尾到头的顺序返回一个ArrayList。
 * 顺序读取，然后翻转集合
 *
 */
public class _3_PrintLinkedFromEndToHead {

    public static void main(String[] args) {

        new _3_PrintLinkedFromEndToHead().test();
    }
    public void test(){

        ListNode listNode = initListNode();
        printListFromTailToHead(listNode);
    }
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {

        ArrayList<Integer> integers = new ArrayList<>();
        while (listNode!=null){

            integers.add(listNode.val);
            listNode = listNode.next;
        }
        Collections.reverse(integers);

        System.out.println(integers);
        return integers;
    }
    public ListNode initListNode(){

        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(4);
        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
        return listNode1;
    }

    public class ListNode {
        int val;
        ListNode next = null;

               ListNode(int val) {
           this.val = val;
        }
    }
}
